/*
 * Created on 10/06/2006
 */
package jmine.tec.batch.event.domain;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import jmine.tec.batch.context.BatchExecutionContext;
import jmine.tec.batch.domain.MPhase;
import jmine.tec.batch.domain.ProcessingUnit;
import jmine.tec.persist.annotation.DiscriminatorComment;
import jmine.tec.persist.annotation.Index;
import jmine.tec.persist.schema.api.IndexOrder;

import org.hibernate.annotations.ForeignKey;

import bancosys.tec.component.Documentation;

/**
 * @author Frank Cara
 */
@Entity
@DiscriminatorValue("PROCESSING_UNIT")
@DiscriminatorComment("EVENTO DE UNIDADE DE PROCESSAMENTO")
public class ProcessingUnitEvent extends Event {

    public static final String CONTEXT_ATTRIBUTE_PHASE = "phase";

    public static final String CONTEXT_ATTRIBUTE_PHASE_MNEMO = "phase.mnemonico";

    public static final String CONTEXT_ATTRIBUTE_PROCESSING_UNIT = "phase.processing.unit";

    public static final String CONTEXT_ATTRIBUTE_PROCESSING_UNIT_ELEMENT = "phase.processing.unit.element";

    private ProcessingUnit<?> processingUnit;

    /**
     * Constructor.
     */
    public ProcessingUnitEvent() {
        super();
    }

    /**
     * Constructor
     * 
     * @param id o id gerado para o evento.
     */
    public ProcessingUnitEvent(long id) {
        super(id);
    }

    /**
     * @return Retorna a unidade de processamento.
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "COD_PROCESS_UNIT")
    @ForeignKey(name = "FK_PROUNI_EVENT")
    @Index(columns = "COD_PROCESS_UNIT", suffix = "1", orders = IndexOrder.ASC)
    @Documentation("CODIGO DA UNIDADE DE PROCESSAMENTO.")
    public ProcessingUnit<?> getProcessingUnit() {
        return this.processingUnit;
    }

    /**
     * Seta a unidade de processamento do evento.
     * 
     * @param processingUnit a unidade de processamento do evento.
     */
    public void setProcessingUnit(ProcessingUnit<?> processingUnit) {
        this.processingUnit = processingUnit;
    }

    /**
     * Utilizado para setar valores do contexto no evento.
     * 
     * @param context o KernelContext.
     */
    @Override
    public void acquireContextData(BatchExecutionContext context) {
        super.acquireContextData(context);

        MPhase mphase = (MPhase) context.getAttribute(CONTEXT_ATTRIBUTE_PHASE);
        if (mphase != null) {
            this.setMnemonico(mphase.getMnemonico());
        } else {
            String mnemonico = (String) context.getAttribute(CONTEXT_ATTRIBUTE_PHASE_MNEMO);
            this.setMnemonico(mnemonico);
        }

        ProcessingUnit<?> pu = (ProcessingUnit<?>) context.getAttribute(CONTEXT_ATTRIBUTE_PROCESSING_UNIT);

        this.setProcessingUnit(pu);
    }
}
